// 修改 Chatserver.cpp
#include "ChatServer.hpp"
#include "ChatService.hpp"
#include "muduo/Log.hpp"
#include "WebSocket.hpp"
#include <nlohmann/json.hpp>

extern Log lg;
using json = nlohmann::json;

ChatServer::ChatServer(EventLoop *loop, const InetAddress &listenAddr, const std::string &nameArg)
    : _server(listenAddr.port()),
      _http_server(loop, listenAddr.port() + 1),  // HTTP 服务器使用不同端口
      _loop(loop) {
    
    // 注册 TCP 连接回调
    _server.SetCounnectedCallback(std::bind(&ChatServer::on_connection, this, std::placeholders::_1));
    // _server.SetMessageCallback(std::bind(&ChatServer::on_message, this, std::placeholders::_1, 
    //                                     std::placeholders::_2, std::placeholders::_3));
    _server.SetThreadCount(4);
    
    // 注册 HTTP 请求回调
    // _http_server.setRequestCallback(std::bind(&ChatServer::on_http_request, this,
    //                                          std::placeholders::_1, std::placeholders::_2,
    //                                          std::placeholders::_3, std::placeholders::_4,
    //                                          std::placeholders::_5));
    
    lg.info("ChatServer initialized on port %d, HTTP server on port %d", 
            listenAddr.port(), listenAddr.port() + 1);
}

void ChatServer::start(){
    _server.Start();
    // HTTP 服务器会自动启动
    lg.info("ChatServer started");
}

void ChatServer::on_connection(const PtrConnection &conn){
    if(!conn->Connected()){
        ChatService::instance().client_close_exception(conn);
        conn->Shutdown();
        lg.info("Client disconnected, connection closed");
    } else {
        lg.info("New client connected, connection established");
    }
}

void ChatServer::on_message(const PtrConnection &conn, Buffer *buffer, Timestamp time){
    try {
        std::string buf = buffer->ReadAsStringAndPop(buffer->ReadAbleSize());
        lg.debug("Received message: %s", buf.c_str());
        
        // 检查是否是 WebSocket 握手请求
        if (buf.find("GET") == 0 && buf.find("Upgrade: websocket") != std::string::npos) {
            std::string response;
            if (WebSocket::handleHandshake(buf, response)) {
                conn->Send(response.c_str(), response.length());
                // 升级连接为 WebSocket
                // 这里需要修改 Connection 类以支持协议升级
                lg.info("WebSocket handshake successful");
            } else {
                lg.error("WebSocket handshake failed");
                conn->Shutdown();
            }
            return;
        }
        
        json js = json::parse(buf);
        auto msg_Handler = ChatService::instance().get_Handler(js["msgid"].get<int>());
        msg_Handler(conn, js, time);
    } catch (const json::parse_error& e) {
        lg.error("JSON parse error: %s", e.what());
        conn->Send("{\"error\":\"invalid json format\"}", 32);
    } catch (const std::exception& e) {
        lg.error("Exception in on_message: %s", e.what());
        conn->Shutdown();
    } catch (...) {
        lg.error("Unknown exception in on_message");
        conn->Shutdown();
    }
}

void ChatServer::on_http_request(const std::string& method, 
                                const std::string& path, 
                                const std::map<std::string, std::string>& headers,
                                const std::string& body,
                                std::string& response) {
    
    lg.debug("HTTP Request: %s %s", method.c_str(), path.c_str());
    
    if (method == "GET" && path == "/") {
        // 返回聊天网页
        std::string html = R"(
<!DOCTYPE html>
<html>
<head>
    <title>Chat Application</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; }
        #messages { border: 1px solid #ccc; height: 300px; overflow-y: scroll; padding: 10px; }
        #input { margin-top: 10px; width: 300px; }
        #send { margin-left: 10px; }
    </style>
</head>
<body>
    <h1>Chat Application</h1>
    <div id="messages"></div>
    <input type="text" id="input" placeholder="Type your message here...">
    <button id="send">Send</button>
    
    <script>
        const ws = new WebSocket('ws://localhost:8080');
        const messages = document.getElementById('messages');
        const input = document.getElementById('input');
        const sendButton = document.getElementById('send');
        
        ws.onopen = function() {
            messages.innerHTML += '<p>Connected to chat server</p>';
        };
        
        ws.onmessage = function(event) {
            const data = JSON.parse(event.data);
            messages.innerHTML += '<p><strong>' + (data.from || 'System') + ':</strong> ' + data.message + '</p>';
            messages.scrollTop = messages.scrollHeight;
        };
        
        ws.onclose = function() {
            messages.innerHTML += '<p>Disconnected from chat server</p>';
        };
        
        sendButton.onclick = function() {
            if (input.value) {
                ws.send(JSON.stringify({
                    msgid: 3, // ONE_CHAT_MSG
                    to: 1, // 发送给用户1作为示例
                    message: input.value
                }));
                input.value = '';
            }
        };
        
        input.onkeypress = function(e) {
            if (e.key === 'Enter') {
                sendButton.click();
            }
        };
    </script>
</body>
</html>
        )";
        
        response = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: " + 
                   std::to_string(html.length()) + "\r\n\r\n" + html;
    } else if (method == "GET" && path == "/ws") {
        // WebSocket 升级请求应该在 on_message 中处理
        response = "HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\n\r\n";
    } else {
        response = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n";
    }
}